//
//  MHHomeMainViewController.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/24.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHHomeMainViewController.h"
#import "MHHomeCategory.h"
#import "MHComicIntroduct.h"
#import "WaterFlowLayout.h"
#import "UIImage+Addiction.h"
#import "MHWaterFlowLayoutCell.h"
#import "MHComicDetailViewController.h"
#import "MHBannerViewController.h"
#import <AFNetworking.h>
#define kHomeMainHeader @"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx"

@interface MHHomeMainViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDelegateWaterFlowLayout>
@property (nonatomic, strong) NSMutableArray *homeCategoryArray;
@property (nonatomic, strong) NSMutableArray *comicIntroductArray;
@property (nonatomic, copy) NSString *VisibleIDs;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *sizeArray;
@property (nonatomic, strong) NSMutableArray *bannerArray;
@property (nonatomic, strong) UICollectionReusableView *bannerView;
@property (nonatomic, strong) MHBannerViewController *bannerVC;

@end

@implementation MHHomeMainViewController

- (void)acquireCategoryData
{
    [[AFHTTPRequestOperationManager manager] GET:kHomeMainHeader parameters:[NSDictionary dictionaryWithObjects:@[@"RecommandRank"] forKeys:@[@"method"]] success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        self.homeCategoryArray = [NSMutableArray array];
        self.VisibleIDs = @"";
        for (NSDictionary *dict in responseObject) {
            if ([dict[@"Type"] isEqualToString:@"Book"]) {
                MHHomeCategory *homeCategory = [MHHomeCategory modelWithDict:dict];
                [self.homeCategoryArray addObject:homeCategory];
                self.VisibleIDs = [[self.VisibleIDs stringByAppendingString:homeCategory.VisibleIDs] stringByAppendingString:@"#"];
            }
        }
        [self acquireComicData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)acquireComicData
{
    NSDictionary *param = [NSDictionary dictionaryWithObjects:@[self.VisibleIDs, @"search", @"2"] forKeys:@[@"name", @"method", @"type"]];
    [[AFHTTPRequestOperationManager manager] GET:kHomeMainHeader parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        self.comicIntroductArray = [NSMutableArray array];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (NSDictionary *dict in responseObject) {
            MHComicIntroduct *comicIntroduct = [MHComicIntroduct modelWithDict:dict];
            [self.comicIntroductArray addObject:comicIntroduct];
            if ([comicIntroduct.BookIconOtherURL hasPrefix:@"http://pic.huo80.com/comicui"]) {
                comicIntroduct.imageSize = CGSizeMake(165, 220);
            }
            else
            {
                comicIntroduct.imageSize = [UIImage downloadImageSizeWithURL:comicIntroduct.BookIconOtherURL];
            }
        }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        
        });
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)acquireBannerDate
{
    [[AFHTTPRequestOperationManager manager] GET:@"https://pi.comikon.net/banner/?format=json&platform=ios" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"%@", responseObject[@"results"][0]);
        self.bannerArray = [NSMutableArray array];
        for (NSDictionary *dict in responseObject[@"results"]) {
            if ([dict[@"banner_type"] isEqualToString:@"bookres"]) {
                MHComicIntroduct *comicIntroduct = [MHComicIntroduct modelWithDict:dict];
                [self.bannerArray addObject:comicIntroduct];
            }
        }
        self.bannerVC.imageArray = self.bannerArray;
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)createBannerView
{
    CGFloat bannerH = 44.0 / 64.0 * Width;
    MHBannerViewController *bannerVC = [[MHBannerViewController alloc]init];
    __weak MHHomeMainViewController *test = self;
    bannerVC.buttonClickBlock = ^(NSInteger number)
    {
        MHComicDetailViewController *comicDetailVC = [[MHComicDetailViewController alloc]init];
        comicDetailVC.comicIntroduct = self.bannerArray[number];
        [test.navigationController pushViewController:comicDetailVC animated:YES];
    };
    self.bannerView = [[UICollectionReusableView alloc]initWithFrame:CGRectMake(0, 64, Width, bannerH)];
    [self.bannerView addSubview:bannerVC.contentView];
    self.bannerVC = bannerVC;
    self.bannerView.frame = CGRectMake(0, 0, Width, bannerH);
    [self.collectionView addSubview:self.bannerView];
}

- (void)reloadBanner
{
    static int num = 1;
    if (num == self.bannerArray.count) {
        self.bannerVC.imageArray = self.bannerArray;
    }
    num++;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self acquireCategoryData];
    [self acquireBannerDate];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;

    WaterFlowLayout *water = [[WaterFlowLayout alloc]initWithNumbersOfColumns:2];
    water.minimumInteritemSpacing = 10;
    water.minimumLineSpacing = 10;
    water.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    water.delegate = self;
    water.headerReferenceSize = CGSizeMake(Width, 44.0 / 64.0 * Width);
    
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, Width, Height - 64 - 44) collectionViewLayout:water];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    [self.collectionView registerClass:[MHWaterFlowLayoutCell class] forCellWithReuseIdentifier:@"waterFlowLayout"];
    
    [self createBannerView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadBanner) name:@"imageUrl" object:nil];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.comicIntroductArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHWaterFlowLayoutCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"waterFlowLayout" forIndexPath:indexPath];
    cell.comicIntroct = self.comicIntroductArray[indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(WaterFlowLayout *)layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHComicIntroduct *comicIntroduct = self.comicIntroductArray[indexPath.item];
    CGSize size = comicIntroduct.imageSize;
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHComicDetailViewController *comicDetailVC = [[MHComicDetailViewController alloc]init];
    comicDetailVC.comicIntroduct = self.comicIntroductArray[indexPath.row];
    [self.navigationController pushViewController:comicDetailVC animated:YES];
}

@end
